﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace UrlChecker.Setting
{
    public partial class AddURL : Form
    {
        public string url="";
        public string gid = "";

        public AddURL()
        {
            InitializeComponent();
        }

        public AddURL(string id, string uri)
        {
            InitializeComponent();
            gid = id;
            url = uri;
        }

        private void AddURL_Load(object sender, EventArgs e)
        {
            DataTable dt = QT.SEO.Group.GetAll(); 
            this.cbbGroup.ValueMember = dt.Columns[0].ToString();
            this.cbbGroup.DisplayMember = dt.Columns[1].ToString();
            this.cbbGroup.DataSource = dt;
            this.cbbGroup.SelectedValue = gid;
            this.tbURL.Text = url;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (this.cbbGroup.SelectedValue == null)
            {
                MessageBox.Show("请选择分组");
                return;
            }

            if (this.tbURL.Text.Length == 0)
            {
                MessageBox.Show("请输入网址");
                return;
            }
            if(!(new Regex(@"(http://){0,1}([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?").IsMatch(this.tbURL.Text)))
            {
                MessageBox.Show("请检查输入的网址是否正确");
                return;
            }

            switch (QT.SEO.URL.Add(this.tbURL.Text, this.cbbGroup.SelectedValue.ToString()))
            {
                case 0:
                case -1:
                    MessageBox.Show("添加失败");
                    break;
                case -2:
                    MessageBox.Show("URL已存在");
                    break;
                default:
                    MessageBox.Show("添加成功");
                    this.url = this.tbURL.Text;
                    this.gid = this.cbbGroup.SelectedValue.ToString();
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                    break;
            }    

            this.Close();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
            this.DialogResult = DialogResult.Cancel;
        }
    }
}
